package com.itheima.tlias84.exception;

import com.itheima.tlias84.utils.ResultUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 全局异常处理器
 * 无法只用try-catch捕获进入Controller之前的异常，但可以使用AOP对Controller进行调用之前的增强
 * 因此@RestControllerAdvice相当于环绕通知Controller
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultUtil handleArithmaticException() {
        return ResultUtil.failure("发生除以0错误");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultUtil handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String defaultMessage = Objects.requireNonNull(e.getFieldError()).getDefaultMessage();
        Object rejectedValue = e.getFieldError().getRejectedValue();
        return ResultUtil.failure(defaultMessage, rejectedValue);
    }

}
